<template>
  <div class="dashboard">
    <!-- 用户切换器 -->
    <UserSwitcher />

    <!-- 错误提示 -->
    <div v-if="store.error" class="error-message">
      {{ store.error }}
      <button @click="store.clearError()" class="close-btn">×</button>
    </div>

    <!-- 用户统计信息 -->
    <div v-if="store.userStats" class="stats-container">
      <h3>我的申请统计</h3>
      <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-number">{{ store.userStats.total }}</div>
          <div class="stat-label">总申请数</div>
        </div>
        <div class="stat-item">
          <div class="stat-number pending">{{ store.userStats.pending }}</div>
          <div class="stat-label">待审批</div>
        </div>
        <div class="stat-item">
          <div class="stat-number completed">{{ store.userStats.completed }}</div>
          <div class="stat-label">已完成</div>
        </div>
        <div class="stat-item">
          <div class="stat-number rejected">{{ store.userStats.rejected }}</div>
          <div class="stat-label">已驳回</div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="dashboard-grid">
      <!-- 员工功能区域 -->
      <div v-if="store.currentUser.role === 'employee'" class="panel">
        <h3>提交新申请</h3>
        <ApplicationForm @success="handleFormSuccess" />
      </div>

      <!-- 待办任务面板 -->
      <div class="panel">
        <h3>我的待办 ({{ store.pendingTasksForCurrentUser.length }})</h3>
        <div v-if="store.pendingTasksForCurrentUser.length" class="task-list">
          <div v-for="app in pagedTodo" :key="app.id" class="task-item">
            <router-link :to="`/application/${app.id}`" class="task-link">
              <div class="task-info">
                <div class="task-title">{{ app.applicantName }}的报销申请</div>
                <div class="task-details">
                  <span class="amount">¥{{ app.amount.toFixed(2) }}</span>
                  <span class="expense-type">{{ expenseTypeLabel(app.expenseType) }}</span>
                </div>
                <div class="task-status">
                  <span :class="`status-${app.status.toLowerCase()}`">
                    {{ statusText(app.status) }}
                  </span>
                </div>
                <!-- 状态提示信息 -->
                <div v-if="getStatusMessage(app.status)" class="status-hint">
                  {{ getStatusMessage(app.status) }}
                </div>
              </div>
            </router-link>
          </div>
        </div>
        <p v-else class="empty-message">没有待处理的任务。</p>
        <div class="pagination" v-if="store.pendingTasksForCurrentUser.length > todoPageSize">
          <button
            @click="handleTodoPageChange(todoCurrentPage - 1)"
            :disabled="todoCurrentPage === 1"
          >
            上一页
          </button>
          <span>第 {{ todoCurrentPage }} 页</span>
          <button
            @click="handleTodoPageChange(todoCurrentPage + 1)"
            :disabled="todoCurrentPage === todoTotalPages"
          >
            下一页
          </button>
        </div>
      </div>

      <!-- 我的申请面板 -->
      <div class="panel">
        <h3>我提交的申请 ({{ store.mySubmissions.length }})</h3>
        <div v-if="store.mySubmissions.length" class="submission-list">
          <div v-for="app in pagedSubmissions" :key="app.id" class="submission-item">
            <router-link :to="`/application/${app.id}`" class="submission-link">
              <div class="submission-info">
                <div class="submission-title">{{ app.description }}</div>
                <div class="submission-details">
                  <span class="amount">¥{{ app.amount.toFixed(2) }}</span>
                  <span class="expense-type">{{ expenseTypeLabel(app.expenseType) }}</span>
                </div>
                <div class="submission-status">
                  <span :class="`status-${app.status.toLowerCase()}`">
                    {{ statusText(app.status) }}
                  </span>
                </div>
                <!-- 状态提示信息 -->
                <div v-if="getStatusMessage(app.status)" class="status-hint">
                  {{ getStatusMessage(app.status) }}
                </div>
              </div>
            </router-link>
          </div>
        </div>
        <p v-else class="empty-message">您还没有提交任何申请。</p>
        <div class="pagination" v-if="store.mySubmissions.length > pageSize">
          <button @click="handlePageChange(currentPage - 1)" :disabled="currentPage === 1">
            上一页
          </button>
          <span>第 {{ currentPage }} 页</span>
          <button @click="handlePageChange(currentPage + 1)" :disabled="currentPage === totalPages">
            下一页
          </button>
        </div>
      </div>

      <!-- 被驳回的申请（仅员工可见） -->
      <div
        v-if="store.currentUser.role === 'employee' && store.rejectedApplications.length"
        class="panel"
      >
        <h3>被驳回的申请 ({{ store.rejectedApplications.length }})</h3>
        <div class="rejected-list">
          <div v-for="app in pagedRejected" :key="app.id" class="rejected-item">
            <div class="rejected-info">
              <div class="rejected-title">{{ app.description }}</div>
              <div class="rejected-details">
                <span class="amount">¥{{ app.amount.toFixed(2) }}</span>
                <span class="expense-type">{{ expenseTypeLabel(app.expenseType) }}</span>
              </div>
              <div class="rejected-actions">
                <router-link :to="`/application/${app.id}`" class="btn-view">查看详情</router-link>
                <button @click="handleEdit(app)" class="btn-edit" :disabled="loading">
                  编辑申请
                </button>
                <button @click="handleResubmit(app.id)" class="btn-resubmit" :disabled="loading">
                  重新提交
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="pagination" v-if="store.rejectedApplications.length > rejectedPageSize">
          <button
            @click="handleRejectedPageChange(rejectedCurrentPage - 1)"
            :disabled="rejectedCurrentPage === 1"
          >
            上一页
          </button>
          <span>第 {{ rejectedCurrentPage }} 页</span>
          <button
            @click="handleRejectedPageChange(rejectedCurrentPage + 1)"
            :disabled="rejectedCurrentPage === rejectedTotalPages"
          >
            下一页
          </button>
        </div>
      </div>

      <!-- 可撤销的申请（仅员工可见） -->
      <div
        v-if="store.currentUser.role === 'employee' && store.cancellableApplications.length"
        class="panel"
      >
        <h3>可撤销的申请 ({{ store.cancellableApplications.length }})</h3>
        <div class="cancellable-list">
          <div v-for="app in pagedCancellable" :key="app.id" class="cancellable-item">
            <div class="cancellable-info">
              <div class="cancellable-title">{{ app.description }}</div>
              <div class="cancellable-details">
                <span class="amount">¥{{ app.amount.toFixed(2) }}</span>
                <span class="expense-type">{{ expenseTypeLabel(app.expenseType) }}</span>
                <span class="status">{{ statusText(app.status) }}</span>
              </div>
              <div class="cancellable-actions">
                <router-link :to="`/application/${app.id}`" class="btn-view">查看详情</router-link>
                <button @click="handleCancel(app)" class="btn-cancel" :disabled="loading">
                  撤销申请
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="pagination" v-if="store.cancellableApplications.length > cancelPageSize">
          <button
            @click="handleCancelPageChange(cancelCurrentPage - 1)"
            :disabled="cancelCurrentPage === 1"
          >
            上一页
          </button>
          <span>第 {{ cancelCurrentPage }} 页</span>
          <button
            @click="handleCancelPageChange(cancelCurrentPage + 1)"
            :disabled="cancelCurrentPage === cancelTotalPages"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

    <!-- 撤销确认对话框 -->
    <el-dialog
      v-model="showCancelDialog"
      title="撤销申请"
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <CancelApplication
        v-if="selectedApplication"
        :application="selectedApplication"
        @cancel="handleCancelCancel"
        @success="handleCancelSuccess"
      />
    </el-dialog>

    <!-- 编辑申请对话框 -->
    <el-dialog
      v-model="showEditDialog"
      title="编辑申请"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <EditableApplicationForm
        v-if="selectedApplication"
        :application="selectedApplication"
        @cancel="handleEditCancel"
        @success="handleEditSuccess"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, computed } from 'vue'
import { useApplicationStore } from '@/store/application'
import UserSwitcher from '@/components/UserSwitcher.vue'
import ApplicationForm from '@/components/ApplicationForm.vue'
import CancelApplication from '@/components/CancelApplication.vue'
import EditableApplicationForm from '@/components/EditableApplicationForm.vue'
import { STATUS_LABELS, EXPENSE_TYPE_LABELS } from '@/services/models'
import type { ReimbursementApplication } from '@/services/models'

const store = useApplicationStore()
const loading = ref(false)
const showCancelDialog = ref(false)
const showEditDialog = ref(false)
const selectedApplication = ref<ReimbursementApplication | null>(null)

// 状态文本
const statusText = (status: string) => STATUS_LABELS[status as keyof typeof STATUS_LABELS] || '未知'

// 费用类型标签
const expenseTypeLabel = (type: string) =>
  EXPENSE_TYPE_LABELS[type as keyof typeof EXPENSE_TYPE_LABELS] || '未知'

// 状态提示信息
const getStatusMessage = (status: string) => {
  switch (status) {
    case 'PENDING_HEAD_REVIEW':
      return '等待部门主管审批'
    case 'PENDING_FINANCE_REVIEW':
      return '已进入财务审核阶段'
    case 'PENDING_GM_REVIEW':
      return '已进入总经理终审阶段'
    case 'COMPLETED':
      return '审批已完成，将自动打款'
    case 'REJECTED':
      return '申请已被驳回'
    case 'CANCELLED':
      return '申请已被撤销'
    default:
      return null
  }
}

// 重新提交申请
const handleResubmit = async (applicationId: string) => {
  try {
    await store.resubmitApplication(applicationId)
    alert('申请重新提交成功！已进入部门主管审批流程。')
  } catch (error: unknown) {
    alert(`重新提交失败：${error instanceof Error ? error.message : '未知错误'}`)
  }
}

// 撤销申请
const handleCancel = (application: ReimbursementApplication) => {
  selectedApplication.value = application
  showCancelDialog.value = true
}

// 撤销成功处理
const handleCancelSuccess = () => {
  showCancelDialog.value = false
  selectedApplication.value = null
}

// 取消撤销操作
const handleCancelCancel = () => {
  showCancelDialog.value = false
  selectedApplication.value = null
}

// 编辑申请
const handleEdit = (application: ReimbursementApplication) => {
  selectedApplication.value = application
  showEditDialog.value = true
}

// 编辑成功处理
const handleEditSuccess = () => {
  showEditDialog.value = false
  selectedApplication.value = null
}

// 取消编辑操作
const handleEditCancel = () => {
  showEditDialog.value = false
  selectedApplication.value = null
}

// 分页相关变量
const pageSize = 10 // 每页10条
const currentPage = ref(1) // 当前页
// 计算当前页要显示的"我提交的申请"
const pagedSubmissions = computed(() => {
  const start = (currentPage.value - 1) * pageSize
  const end = start + pageSize
  return store.mySubmissions.slice(start, end)
})
// 计算总页数
const totalPages = computed(() => Math.ceil(store.mySubmissions.length / pageSize))

// 页码切换处理，防止越界
function handlePageChange(page: number) {
  if (page < 1 || page > totalPages.value) return
  currentPage.value = page
}

// 可撤销申请分页相关变量
const cancelPageSize = 10 // 每页10条
const cancelCurrentPage = ref(1) // 当前页
// 计算当前页要显示的可撤销申请
const pagedCancellable = computed(() => {
  const start = (cancelCurrentPage.value - 1) * cancelPageSize
  const end = start + cancelPageSize
  return store.cancellableApplications.slice(start, end)
})
// 计算总页数
const cancelTotalPages = computed(() =>
  Math.ceil(store.cancellableApplications.length / cancelPageSize),
)
// 页码切换处理，防止越界
function handleCancelPageChange(page: number) {
  if (page < 1 || page > cancelTotalPages.value) return
  cancelCurrentPage.value = page
}

// 被驳回申请分页相关变量
const rejectedPageSize = 10
const rejectedCurrentPage = ref(1)
const pagedRejected = computed(() => {
  const start = (rejectedCurrentPage.value - 1) * rejectedPageSize
  const end = start + rejectedPageSize
  return store.rejectedApplications.slice(start, end)
})
const rejectedTotalPages = computed(() =>
  Math.ceil(store.rejectedApplications.length / rejectedPageSize),
)
function handleRejectedPageChange(page: number) {
  if (page < 1 || page > rejectedTotalPages.value) return
  rejectedCurrentPage.value = page
}

// 待办任务分页相关变量
const todoPageSize = 10
const todoCurrentPage = ref(1)
const pagedTodo = computed(() => {
  const start = (todoCurrentPage.value - 1) * todoPageSize
  const end = start + todoPageSize
  return store.pendingTasksForCurrentUser.slice(start, end)
})
const todoTotalPages = computed(() =>
  Math.ceil(store.pendingTasksForCurrentUser.length / todoPageSize),
)
function handleTodoPageChange(page: number) {
  if (page < 1 || page > todoTotalPages.value) return
  todoCurrentPage.value = page
}

// 处理申请表单提交成功事件
async function handleFormSuccess(application) {
  // 刷新我的申请列表（如fetchApplications为异步则await，否则可直接调用）
  if (typeof store.fetchApplications === 'function') {
    const result = store.fetchApplications()
    if (result instanceof Promise) {
      await result
    }
  }
  // 弹窗提示（Element Plus全局ElMessage更健壮）
  if (typeof window.ElMessage === 'function') {
    window.ElMessage({
      type: 'success',
      message: '申请提交成功，已加入我的申请列表！',
      duration: 2500,
    })
  }
  // 重置分页到第一页，保证用户能看到最新数据
  currentPage.value = 1
}

// 组件挂载时加载数据
onMounted(async () => {
  await store.fetchApplications()
  await store.fetchUserStats()
})
</script>

<style scoped>
.dashboard {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.error-message {
  background: #e74c3c;
  color: white;
  padding: 12px 16px;
  border-radius: 6px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.close-btn {
  background: none;
  border: none;
  color: white;
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
}

.stats-container {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.stats-container h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 15px;
}

.stat-item {
  text-align: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.stat-number.pending {
  color: #f39c12;
}

.stat-number.completed {
  color: #2ecc71;
}

.stat-number.rejected {
  color: #e74c3c;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.dashboard-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.panel {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.panel h3 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
}

.task-list,
.submission-list,
.rejected-list,
.cancellable-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.task-item,
.submission-item,
.rejected-item,
.cancellable-item {
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  overflow: hidden;
}

.task-link,
.submission-link {
  display: block;
  padding: 15px;
  text-decoration: none;
  color: inherit;
  transition: background-color 0.3s ease;
}

.task-link:hover,
.submission-link:hover {
  background-color: #f8f9fa;
}

.task-info,
.submission-info,
.rejected-info,
.cancellable-info {
  padding: 15px;
}

.task-title,
.submission-title,
.rejected-title,
.cancellable-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.task-details,
.submission-details,
.rejected-details,
.cancellable-details {
  display: flex;
  gap: 15px;
  margin-bottom: 12px;
  font-size: 14px;
  color: #666;
}

.amount {
  color: #e67e22;
  font-weight: bold;
}

.expense-type {
  color: #666;
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 11px;
}

.task-status,
.submission-status {
  display: flex;
  justify-content: flex-end;
}

.status-pending_head_review,
.status-pending_finance_review,
.status-pending_gm_review {
  color: #f39c12;
  font-weight: bold;
  font-size: 12px;
}

.status-completed {
  color: #2ecc71;
  font-weight: bold;
  font-size: 12px;
}

.status-rejected {
  color: #e74c3c;
  font-weight: bold;
  font-size: 12px;
}

.rejected-actions,
.cancellable-actions {
  display: flex;
  gap: 10px;
}

.btn-view,
.btn-resubmit,
.btn-cancel,
.btn-edit {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  text-decoration: none;
  transition: all 0.3s ease;
}

.btn-view {
  background-color: #3498db;
  color: white;
}

.btn-view:hover {
  background-color: #2980b9;
}

.btn-edit {
  background-color: #f39c12;
  color: white;
}

.btn-edit:hover {
  background-color: #e67e22;
}

.btn-resubmit {
  background-color: #2ecc71;
  color: white;
}

.btn-resubmit:hover {
  background-color: #27ae60;
}

.btn-cancel {
  background-color: #e74c3c;
  color: white;
}

.btn-cancel:hover {
  background-color: #c0392b;
}

.btn-resubmit:disabled,
.btn-cancel:disabled,
.btn-edit:disabled {
  background-color: #bdc3c7;
  cursor: not-allowed;
}

.empty-message {
  color: #666;
  font-style: italic;
  text-align: center;
  padding: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard {
    padding: 10px;
  }

  .dashboard-grid {
    grid-template-columns: 1fr;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .rejected-actions {
    flex-direction: column;
  }
}

.submission-status {
  font-size: 12px;
  margin-top: 4px;
}

.status-hint {
  font-size: 11px;
  color: #666;
  margin-top: 2px;
  font-style: italic;
}

.submission-link:hover .submission-info {
  background-color: #f8f9fa;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 24px;
  gap: 16px; /* 按钮和页码间距 */
}

.pagination button {
  padding: 8px 28px;
  border: none;
  border-radius: 8px;
  background: linear-gradient(135deg, #f0f4fa 0%, #e0e7ef 100%);
  color: #222;
  font-size: 16px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(80, 120, 200, 0.08);
  cursor: pointer;
  transition: all 0.2s;
  outline: none;
}

.pagination button:hover:not(:disabled) {
  background: linear-gradient(135deg, #409eff 0%, #337ecc 100%);
  color: #fff;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.15);
}

.pagination button:disabled {
  background: #f0f0f0;
  color: #bbb;
  cursor: not-allowed;
  box-shadow: none;
}

.pagination span {
  font-size: 16px;
  color: #333;
  font-weight: 500;
  min-width: 60px;
  text-align: center;
  letter-spacing: 2px;
}

.node-icon {
  box-shadow:
    0 2px 8px rgba(0, 0, 0, 0.06),
    0 0 0 0 #409eff;
  transition: all 0.3s;
}
.step:hover .node-icon {
  box-shadow:
    0 4px 16px rgba(64, 158, 255, 0.18),
    0 0 0 6px #eaf4ff;
  filter: none;
}

.node-name {
  white-space: nowrap;
  text-align: center;
}

.step {
  width: 120px;
}

.steps-base-line,
.steps-active-line {
  position: absolute;
  top: 36px;
  left: calc(54px / 2); /* 圆的宽度一半 */
  right: calc(54px / 2);
  height: 5px;
  background: #e5e7eb;
  border-radius: 3px;
  z-index: 1;
}

.steps-active-line {
  background: linear-gradient(90deg, #2ecc71 0%, #27ae60 100%);
  z-index: 2;
  transition: width 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 2px 8px rgba(46, 204, 113, 0.1);
}
</style>
